package cn.darxs.noquestion.controller;

import cn.darxs.noquestion.common.Response;
import cn.darxs.noquestion.common.ResponseStateCode;
import cn.darxs.noquestion.entity.Admin;
import cn.darxs.noquestion.entity.Renter;
import cn.darxs.noquestion.entity.Replier;
import cn.darxs.noquestion.entity.User;
import cn.darxs.noquestion.service.AdminService;
import cn.darxs.noquestion.service.RenterService;
import cn.darxs.noquestion.service.ReplierService;
import cn.darxs.noquestion.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/userAccount")
public class UserAccountController {
    @Autowired
    RenterService renterService;
    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;
    @Autowired
    ReplierService replierService;

    @GetMapping("/page/{index}/count/{count}")
    public Response getRenterByPage(HttpServletRequest request, @PathVariable long index, @PathVariable long count) {

        Object status = request.getSession().getAttribute("status");
        Object operatorIdObj = request.getSession().getAttribute("userId");
        long operatorID = 0L;
        Response httpResponseEntity = new Response();
        if(operatorIdObj==null) {
        } else {
            operatorID = Long.parseLong( operatorIdObj.toString());
        }
        if (status == null) {
            httpResponseEntity.setCode(ResponseStateCode.NO_LOGIN);
            httpResponseEntity.setMessage("客户未登录");
        } else if (!status.equals("renter")) {
            httpResponseEntity.setCode(ResponseStateCode.NOT_RENTER);
            httpResponseEntity.setMessage("权限错误");
        } else {
            LambdaQueryWrapper<User> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.orderByDesc(User::getCreateTime)
                    .eq(User::getRenterId,operatorID);
            IPage<User> page = new Page<>(index, count);
            IPage<User> allUsers = userService.page(page, likeWrapper);
            if (allUsers == null) {
                httpResponseEntity.setCode(ResponseStateCode.RENTER_QUERY_FAILURE);
                httpResponseEntity.setMessage("分页查询失败");
            } else {
                httpResponseEntity.setCode(ResponseStateCode.OPERATION_SUCCEED);
                httpResponseEntity.setMessage("分页查询成功");
                httpResponseEntity.setData(allUsers);
            }
        }
        return httpResponseEntity;
    }

    @GetMapping("/page/{index}/count/{count}/with/{info}")
    public Response getRenterByPageWithInfo(HttpServletRequest request, @PathVariable long index, @PathVariable long count, @PathVariable String info) {

        Object status = request.getSession().getAttribute("status");
        Object operatorIdObj = request.getSession().getAttribute("userId");
        long operatorID = 0L;
        Response httpResponseEntity = new Response();
        if(operatorIdObj==null) {
        } else {
            operatorID = Long.parseLong( operatorIdObj.toString());
        }
        if (status == null) {
            httpResponseEntity.setCode(ResponseStateCode.NO_LOGIN);
            httpResponseEntity.setMessage("客户未登录");
        } else if (!status.equals("renter")) {
            httpResponseEntity.setCode(ResponseStateCode.NOT_ADMIN);
            httpResponseEntity.setMessage("权限错误");
        } else {
            LambdaQueryWrapper<User> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(User::getRenterId,operatorID)
                    .like(User::getUsername, info)
                    .or().like(User::getName, info)
                    .or().like(User::getInfo, info)
                    .orderByDesc(User::getCreateTime);
            IPage<User> page = new Page<>(index, count);
            IPage<User> allUsers = userService.page(page, likeWrapper);
            if (allUsers == null) {
                httpResponseEntity.setCode(ResponseStateCode.RENTER_QUERY_FAILURE);
                httpResponseEntity.setMessage("分页查询失败");
            } else {
                httpResponseEntity.setCode(ResponseStateCode.OPERATION_SUCCEED);
                httpResponseEntity.setMessage("分页查询成功");
                httpResponseEntity.setData(allUsers);
            }
        }
        return httpResponseEntity;
    }

    @GetMapping("/all")
    public Response getAllRenter(HttpServletRequest request) {
        Object status = request.getSession().getAttribute("status");
        Object operatorIdObj = request.getSession().getAttribute("userId");
        long operatorID = 0L;
        Response httpResponseEntity = new Response();
        if(operatorIdObj==null) {
        } else {
            operatorID = Long.parseLong( operatorIdObj.toString());
        }
        if (status == null) {
            httpResponseEntity.setCode(ResponseStateCode.NO_LOGIN);
            httpResponseEntity.setMessage("客户未登录");
        } else if (!status.equals("renter")) {
            httpResponseEntity.setCode(ResponseStateCode.NOT_ADMIN);
            httpResponseEntity.setMessage("权限错误");
        } else {
            LambdaQueryWrapper<User> renterWrapper = new LambdaQueryWrapper<>();
            renterWrapper.eq(User::getRenterId,operatorID);
            List<User> allUsers = userService.list(renterWrapper);
            if (allUsers == null) {
                httpResponseEntity.setCode(ResponseStateCode.RENTER_QUERY_FAILURE);
                httpResponseEntity.setMessage("查询失败");
            } else {
                httpResponseEntity.setCode(ResponseStateCode.OPERATION_SUCCEED);
                httpResponseEntity.setMessage("查询成功");
                httpResponseEntity.setData(allUsers);
            }
        }
        return httpResponseEntity;
    }

    @PutMapping("/create")
    public Response createAccount(HttpServletRequest request, @RequestBody User newUser) {

        Object status = request.getSession().getAttribute("status");
        Object operatorIdObj = request.getSession().getAttribute("userId");
        long operatorID = 0L;
        Response httpResponseEntity = new Response();
        if(operatorIdObj==null) {
        } else {
            operatorID = Long.parseLong( operatorIdObj.toString());
        }

        if (status == null) {
            httpResponseEntity.setCode(ResponseStateCode.NO_LOGIN);
            httpResponseEntity.setMessage("客户未登录");
        } else if (!status.equals("renter")) {
            httpResponseEntity.setCode(ResponseStateCode.NOT_ADMIN);
            httpResponseEntity.setMessage("权限错误");
        } else {
            LambdaQueryWrapper<User> sameWrapper = new LambdaQueryWrapper<>();
            sameWrapper.eq(User::getUsername, newUser.getUsername());
            User sameUser = userService.getOne(sameWrapper);

            LambdaQueryWrapper<Admin> adminWrapper = new LambdaQueryWrapper<>();
            adminWrapper.eq(Admin::getUsername, newUser.getUsername());
            Admin adminUser = adminService.getOne(adminWrapper);

            LambdaQueryWrapper<Renter> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(Renter::getUsername, newUser.getUsername());
            Renter renterUser = renterService.getOne(userWrapper);

            LambdaQueryWrapper<Replier> replierWrapper = new LambdaQueryWrapper<>();
            replierWrapper.eq(Replier::getUsername, newUser.getUsername());
            Replier replierUser = replierService.getOne(replierWrapper);

            if (sameUser == null && adminUser == null && renterUser == null && replierUser == null) {
                newUser.clearSystemInfo();
                newUser.setRenterId(operatorID);
                boolean isSuccess = userService.save(newUser);
                if (isSuccess) {
                    httpResponseEntity.setCode(ResponseStateCode.OPERATION_SUCCEED);
                    httpResponseEntity.setMessage("创建成功");
                } else {
                    httpResponseEntity.setCode(ResponseStateCode.RENTER_CREATE_FAILURE);
                    httpResponseEntity.setMessage("未知错误");
                }
            } else {
                httpResponseEntity.setCode(ResponseStateCode.RENTER_CREATE_FAILURE);
                httpResponseEntity.setMessage("账户名重复");
            }
        }

        return httpResponseEntity;
    }

    @PutMapping("/update")
    public Response updateAccount(HttpServletRequest request, @RequestBody User newUser) {

        Object status = request.getSession().getAttribute("status");
        Object operatorIdObj = request.getSession().getAttribute("userId");
        long operatorID = 0L;
        Response httpResponseEntity = new Response();
        if(operatorIdObj==null) {
        } else {
            operatorID = Long.parseLong( operatorIdObj.toString());
        }
        if (status == null) {
            httpResponseEntity.setCode(ResponseStateCode.NO_LOGIN);
            httpResponseEntity.setMessage("客户未登录");
        } else if (!status.equals("renter")) {
            httpResponseEntity.setCode(ResponseStateCode.NOT_ADMIN);
            httpResponseEntity.setMessage("权限错误");
        } else {
            LambdaQueryWrapper<User> sameIDWrapper = new LambdaQueryWrapper<>();
            sameIDWrapper.eq(User::getId, newUser.getId());
            User oldUser = userService.getOne(sameIDWrapper);

            if (oldUser != null) {
                LambdaQueryWrapper<User> sameWrapper = new LambdaQueryWrapper<>();
                sameWrapper.eq(User::getUsername, newUser.getUsername());
                User sameUser = userService.getOne(sameWrapper);

                LambdaQueryWrapper<Admin> adminWrapper = new LambdaQueryWrapper<>();
                adminWrapper.eq(Admin::getUsername, newUser.getUsername());
                Admin adminUser = adminService.getOne(adminWrapper);

                LambdaQueryWrapper<Renter> userWrapper = new LambdaQueryWrapper<>();
                userWrapper.eq(Renter::getUsername, newUser.getUsername());
                Renter renterUser = renterService.getOne(userWrapper);

                LambdaQueryWrapper<Replier> replierWrapper = new LambdaQueryWrapper<>();
                replierWrapper.eq(Replier::getUsername, newUser.getUsername());
                Replier replierUser = replierService.getOne(replierWrapper);

                if ((sameUser == null && adminUser == null && renterUser == null && replierUser == null)
                        || Objects.equals(Objects.requireNonNull(newUser).getId(), newUser.getId())) {
                    newUser.clearTimeInfo();
                    newUser.setRenterId(operatorID);
                    boolean success = userService.updateById(newUser);
                    if (success) {
                        httpResponseEntity.setCode(ResponseStateCode.OPERATION_SUCCEED);
                        httpResponseEntity.setMessage("更新成功");
                    } else {
                        httpResponseEntity.setCode(ResponseStateCode.RENTER_CREATE_FAILURE);
                        httpResponseEntity.setMessage("未知错误");
                    }
                } else {
                    httpResponseEntity.setCode(ResponseStateCode.RENTER_CREATE_FAILURE);
                    httpResponseEntity.setMessage("账户名重复");
                }
            } else {
                httpResponseEntity.setCode(ResponseStateCode.RENTER_ID_NOT_EXIST);
                httpResponseEntity.setMessage("账户不存在");
            }
        }

        return httpResponseEntity;
    }

    @DeleteMapping("/{id}")
    public Response deleteAccount(HttpServletRequest request, @PathVariable long id) {

        Object status = request.getSession().getAttribute("status");
        Object operatorIdObj = request.getSession().getAttribute("userId");
        long operatorID = 0L;
        Response httpResponseEntity = new Response();
        if(operatorIdObj==null) {
            httpResponseEntity.setCode(ResponseStateCode.NO_LOGIN);
            httpResponseEntity.setMessage("客户未登录");
            return httpResponseEntity;
        } else {
            operatorID = Long.parseLong( operatorIdObj.toString());
        }

        if (status == null) {
            httpResponseEntity.setCode(ResponseStateCode.NO_LOGIN);
            httpResponseEntity.setMessage("客户未登录");
        } else if (!status.equals("renter")) {
            httpResponseEntity.setCode(ResponseStateCode.NOT_ADMIN);
            httpResponseEntity.setMessage("权限错误");
        } else {
            LambdaQueryWrapper<User> sameIDWrapper = new LambdaQueryWrapper<>();
            sameIDWrapper.eq(User::getId, id).eq(User::getRenterId,operatorID);
            User oldUser = userService.getOne(sameIDWrapper);

            if (oldUser != null) {
                boolean success = userService.removeById(id);
                if (success) {
                    httpResponseEntity.setCode(ResponseStateCode.OPERATION_SUCCEED);
                    httpResponseEntity.setMessage("删除成功");
                } else {
                    httpResponseEntity.setCode(ResponseStateCode.RENTER_CREATE_FAILURE);
                    httpResponseEntity.setMessage("未知错误");
                }
            } else {
                httpResponseEntity.setCode(ResponseStateCode.RENTER_ID_NOT_EXIST);
                httpResponseEntity.setMessage("账户不存在");
            }
        }

        return httpResponseEntity;
    }


}
